package com.myspring.advice;

import com.myspring.utils.TransactionManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * ClassName: TranscationAdvice
 * Package: com.myspring.advice
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/2/5 16:41
 * @Version 1.0
 */
@Component
@Aspect
public class TransactionAdvice {
    @Autowired
    TransactionManager transactionManager;

    private Logger logger = LogManager.getLogger(TransactionAdvice.class);

    @Around("execution(* com.myspring.service..*.*(..)) && !execution(* com.myspring.service..*.find*(..))")//排除find方法
    public void aroundServiceAdvice(ProceedingJoinPoint pjp) {
        try {
            transactionManager.beginTransaction();
            logger.info("开启事务");
            logger.info("执行{}目标方法", pjp.getSignature());

            pjp.proceed();//执行目标方法

            transactionManager.commit();
            logger.info("提交事务");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            transactionManager.rollback();
            logger.info("回滚事务");
        } finally {
            transactionManager.release();
            logger.info("释放连接");
        }
    }
}